import { useRef } from 'react';
import { history } from 'umi';
import qs from 'query-string';
import { Button, Table, message, Modal, Tooltip } from 'antd';
import SearchAndTable from '@/components/SearchAndTable';
import { ProFormText } from '@ant-design/pro-form';
import { ActionType, ProColumnType } from '@ant-design/pro-table';
import {
    fetchUserCateInfo,
    fetchUserList,
    uploadFile,
    uploadMultipleImport,
} from '@/service/personnelEntry';
import { PageConfigParams } from '@/components/SearchAndTable/interface';
import {
    RequestParams,
    PersonnelEntryState,
    WhetherService,
    IDType,
} from './interface';
import DefaultCollapseHeader from '@/components/SearchAndTable/components/DefaultCollapseHeader';
import styles from './index.scss';
import editIcon from '@/public/tables/edit.png';
import deleteIcon from '@/public/tables/delete.png';
import { deleteUser } from '../../service/personnelEntry';
import { ActionMode } from './components/AddPerson/interface';
import { useRequest } from 'ahooks';
import fetchLocalFile from '@/utils/upload';
import useAutoInjectCateInfo from './hooks/useAutoInjectCateInfo';
import { EditTwoTone, DeleteTwoTone, EyeTwoTone } from '@ant-design/icons';
const columns: ProColumnType<PersonnelEntryState>[] = [
    {
        title: '编号',
        key: 'id',
        dataIndex: 'id',
    },
    {
        title: '用户名',
        key: 'username',
        dataIndex: 'username',
    },
    {
        title: '年龄',
        key: 'age',
        dataIndex: 'age',
        hideInSearch: true,
    },
    {
        title: '所属军队',
        key: 'army_id',
        dataIndex: 'army',
        valueType: 'cascader',
        fieldProps: {
            options: [],
        },
    },
    {
        title: '兵种',
        key: 'corps_id',
        dataIndex: 'corps',
        valueType: 'select',
    },
    {
        title: '是否服役',
        key: 'serve_status',
        dataIndex: 'serve_status_text',
        valueType: 'select',
        valueEnum: {
            [WhetherService.是]: {
                text: WhetherService[WhetherService.是],
            },
            [WhetherService.否]: {
                text: WhetherService[WhetherService.否],
            },
        },
    },
    {
        title: '地址',
        key: 'address',
        dataIndex: 'address',
        hideInSearch: true,
    },
    {
        title: '证件类型',
        key: 'no_type',
        dataIndex: 'no_type_text',
        valueType: 'select',
        valueEnum: {
            [IDType.军人证]: IDType[IDType.军人证],
            [IDType.身份证]: IDType[IDType.身份证],
            [IDType.驾驶证]: IDType[IDType.驾驶证],
        },
    },
    {
        title: '证件编号',
        key: 'no',
        dataIndex: 'no',
    },
    {
        title: '创建时间',
        key: 'creaet_time',
        dataIndex: 'creaet_time',
        hideInSearch: true,
    },
];

const toPersonnelAdd = () => {
    history.push(`/personnelEntry/addPerson`);
};

const toPersonModify = (
    id: PersonnelEntryState['id'] | PersonnelEntryState['id'][],
    mode: ActionMode = ActionMode.One,
) => {
    history.push(`/personnelEntry/modifyPerson?${qs.stringify({ id, mode })}`);
};
export const toPersonnelEntry = () => history.push('/personnelEntry');

export default function PersonnelEntry() {
    const selectedRowsRef = useRef<PersonnelEntryState[]>([]);
    const tableRef = useRef<ActionType>();

    const dataSourceRequest = async ({
        pageSize = 10,
        current = 1,
        ...params
    }: PageConfigParams & RequestParams) => {
        const response = await fetchUserList({
            page: current,
            limit: pageSize,
            ...params,
        });

        if (response.code !== 200) {
            return {
                success: false,
                total: 0,
                data: [],
            };
        }
        const { data, total } = response.data;
        return { data, total: Number(total), success: true };
    };

    const importInformationHandler = async () => {
        const file = await fetchLocalFile('.xls,.xlsx');

        const res = await uploadMultipleImport(file[0]);
        if (res.code !== 200) {
            message.error(res.msg || '上传失败');
            return;
        }
        message.error('上传成功');
    };

    const multipleModifyHandler = () => {
        if (!selectedRowsRef.current.length) {
            message.info('请选择具体列');
            return;
        }
        toPersonModify(
            selectedRowsRef.current.map((item) => item.id),
            ActionMode.Multiple,
        );
    };

    const multipleDeleteHandler = async () => {
        if (!selectedRowsRef.current.length) {
            message.info('请选择具体列');
            return;
        }
        const isDelete = await new Promise((resolve) => {
            Modal.confirm({
                title: '确定删除',
                content: '确定删除此列吗？',
                keyboard: false,
                maskClosable: false,
                onOk: () => resolve(true),
                onCancel: () => resolve(false),
            });
        });

        if (!isDelete) return;
        const res = await deleteUser(
            selectedRowsRef.current.map((item) => item.id),
        );

        if (res.code != 200) {
            message.error(res.msg);
            return;
        }

        message.success('删除成功');
        tableRef.current?.reload();
    };

    const deleteUserHandler = async (id: string | string[]) => {
        const isDelete = await new Promise((resolve) => {
            Modal.confirm({
                title: '确认删除',
                content: '您确定要删除当前记录么？',
                keyboard: false,
                maskClosable: false,
                onOk: () => resolve(true),
                onCancel: () => resolve(false),
            });
        });

        if (!isDelete) return;
        const response = await deleteUser(id);

        if (response.code !== 200) {
            message.error(response.msg);
            return;
        }

        message.success('删除成功');
        tableRef.current?.reload();
    };

    const lookUserHandler = (record: PersonnelEntryState) => {
        history.push(`/personnelEntry/details/${record.id}`);
    };

    const { columns: columnsWithCatelog } = useAutoInjectCateInfo(columns);

    const newColumns = columnsWithCatelog.concat({
        title: '操作',
        hideInSearch: true,
        render: (_, record) => (
            <>
                <Tooltip title="查看">
                    <EyeTwoTone
                        style={{ padding: '0 5px' }}
                        onClick={(e) => {
                            e.stopPropagation();
                            lookUserHandler(record);
                        }}
                        // type="link"
                        // icon={<img src={editIcon} />}
                    />
                </Tooltip>
                <Tooltip title="编辑">
                    <EditTwoTone
                        style={{ padding: '0 5px' }}
                        onClick={(e) => {
                            e.stopPropagation();
                            toPersonModify(record.id);
                        }}
                        // type="link"
                        // icon={<img src={editIcon} />}
                    />
                </Tooltip>
                <Tooltip title="删除">
                    <DeleteTwoTone
                        style={{ padding: '0 5px' }}
                        onClick={(e) => {
                            e.stopPropagation();
                            deleteUserHandler(record.id);
                        }}
                        type="link"
                        // icon={<img src={deleteIcon} />}
                    />
                </Tooltip>
            </>
        ),
    });

    // const toEnrollBookDetails = (record: PersonnelEntryState) => {
    //     history.push(`/personnelEntry/details/${record.id}`);
    // };

    return (
        <>
            <SearchAndTable<PersonnelEntryState, RequestParams>
                columns={newColumns}
                request={dataSourceRequest}
                renderCollapseHeader={(params) => {
                    return (
                        <DefaultCollapseHeader collapseHeader={params}>
                            <ProFormText
                                disabled={params.collapse}
                                name="username"
                                placeholder="请输入用户名"
                            />
                        </DefaultCollapseHeader>
                    );
                }}
                renderController={() => {
                    return (
                        <div className={styles.controller}>
                            <Button
                                type="primary"
                                onClick={() => toPersonnelAdd()}
                            >
                                新增人员
                            </Button>
                            <Button onClick={importInformationHandler}>
                                批量导入
                            </Button>
                            {/* <Button onClick={multipleModifyHandler}>
                                批量编辑
                            </Button> */}
                            <Button onClick={multipleDeleteHandler}>
                                批量删除
                            </Button>
                        </div>
                    );
                }}
                tableProps={{
                    tableAlertRender: false,
                    rowSelection: {
                        selections: [
                            Table.SELECTION_ALL,
                            Table.SELECTION_INVERT,
                        ],
                        onChange: (rows, state) => {
                            selectedRowsRef.current = state;
                        },
                        getCheckboxProps: (record) => ({
                            disabled: Number(record.serve_status) === 0,
                        }),
                    },
                    rowKey: 'id',
                    actionRef: tableRef,
                    // onRow: (record) => {
                    //     return {
                    //         onClick: (event) => {
                    //             toEnrollBookDetails(record);
                    //         }, // 点击行
                    //     };
                    // },
                    scroll: {
                        x: 1000,
                        y: 500,
                        scrollToFirstRowOnChange: true,
                    },
                }}
            />
        </>
    );
}
